import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:flutter/material.dart';

class UnderlineTextField extends StatefulWidget {
  final TextEditingController controller;
  final TextInputType? keyboardType;
  final String? labelText;
  final String hintText;
  final void Function(String)? onChanged;
  final String? Function(String)? validator;
  final VoidCallback? onTap;
  final bool obscureText; // 是否为密码类型

  const UnderlineTextField({
    super.key,
    required this.controller,
    this.keyboardType,
    this.labelText,
    required this.hintText,
    this.onChanged,
    this.validator,
    this.onTap,
    this.obscureText = false,
  });

  @override
  State<UnderlineTextField> createState() => _UnderlineTextFieldState();
}

class _UnderlineTextFieldState extends State<UnderlineTextField> {
  String? errortext;
  bool _isEmpty = true;
  late bool _obscureText;

  @override
  void initState() {
    super.initState();
    _obscureText = widget.obscureText;
  }

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      controller: widget.controller,
      keyboardType: widget.keyboardType,
      obscureText: _obscureText,
      style: context.textTheme.headlineMedium!.copyWith(
        color: context.customColorThemeNonNull.textColor1,
      ),
      decoration: InputDecoration(
        enabledBorder: const UnderlineInputBorder(
          borderSide: BorderSide(color: Color(0xFFEAEAEA)),
        ),
        focusedBorder: const UnderlineInputBorder(
          borderSide: BorderSide(color: Color(0xFF6758D4)),
        ),
        errorBorder: const UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.red),
        ),
        labelText: widget.labelText,
        hintText: widget.hintText,
        hintStyle: context.textTheme.headlineMedium!.copyWith(
          color: context.customColorThemeNonNull.gy4,
        ),
        errorText: errortext,
        // 右侧眼睛按钮
        suffixIcon: widget.obscureText
            ? IconButton(
                icon: Icon(
                  _obscureText
                      ? Icons.visibility_off_outlined
                      : Icons.visibility,
                  color: context.customColorThemeNonNull.textColor2,
                ),
                onPressed: () {
                  setState(() {
                    _obscureText = !_obscureText;
                  });
                },
              )
            : null,
      ),
      onTap: widget.onTap,
      onChanged: _handleChanged,
    );
  }

  void _handleChanged(String value) {
    setState(() {
      _isEmpty = value.isEmpty;
    });

    if (widget.onChanged != null) {
      widget.onChanged!(value);
    }
    if (value.isEmpty) {
      setState(() {
        errortext = null;
      });
      return;
    }
    if (widget.validator != null) {
      final error = widget.validator!(value);
      setState(() {
        errortext = error;
      });
    }
  }
}
